package com.customization.unionpay.market.job;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.PropUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.schedule.BaseCronJob;


/**
 * @author sjm
 * @description 定时（频次要高，例如5分钟/次）根据授权码查询营销日报表台账获取数据（日报流水类型=正常数据/核定金额变更数据），修改已入账金额，已使用金额（清算金额），已请款金额
 */
public class SyncMarketActivityInfoByInternalJob extends BaseCronJob {

    private static final Logger log = LoggerFactory.getLogger(SyncMarketActivityInfoByInternalJob.class);

    @Override
    public void execute() {
        RecordSet rs = new RecordSet();

        try {
            // 营销活动事项台账表单id
            int formId = Integer.parseInt(com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_ledger_form_id"));
            // 查询枚举 活动是否核销
            String selectValueNo =  com.customization.unionpay.market.util.FormDataUtils.getItemValue(formId, "hdsfhx", "否");
            log.info("活动是否核销："+selectValueNo);
            if (StrUtil.isNotBlank(selectValueNo) ) {
                // 营销活动事项台账主表表名
                String ledgerTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(formId);
                log.info("营销活动事项台账主表表名："+ledgerTableName);
                if (StrUtil.isNotBlank(ledgerTableName)) {
                    String sql = "select id,yxpthdsqm as actAuthCode from #{tableName} where hdsfhx = '" + selectValueNo + "' and yxpthdsqm is not null";
                    sql = sql.replace("#{tableName}",ledgerTableName);
                    log.info("sql:"+sql);
                    // 查询营销活动事项台账活动是否核销为否的数据
                    rs.executeQuery(sql);
                    // 建立对应关系
                    while (rs.next()) {
                        String actAuthCode = Util.null2String(rs.getString("actAuthCode"));
                        log.info("actAuthCode:"+actAuthCode);
                        if (!"".equals(actAuthCode)) {
                            JSONObject sumAmountOfMoney = getSumAmountOfMoney(actAuthCode);
                            log.info("sumAmountOfMoney:"+sumAmountOfMoney);
                            if(sumAmountOfMoney != null) {
                                String qs = sumAmountOfMoney.getString("qs");
                                String rz = sumAmountOfMoney.getString("rz");
                                String qk = sumAmountOfMoney.getString("qk");
                                RecordSetTrans rst = new RecordSetTrans();
                                // 开启事务（关闭自动提交）
                                rst.setAutoCommit(false);
                                try {
                                    StringBuilder updateSql = new StringBuilder(" update ");
                                    updateSql.append(ledgerTableName);
                                    updateSql.append(" set ysyje='");
                                    updateSql.append(qs);
                                    updateSql.append("',yrzje='");
                                    updateSql.append(rz);
                                    updateSql.append("',yqkje='");
                                    updateSql.append(qk);
                                    updateSql.append("'  where yxpthdsqm ='");
                                    updateSql.append(actAuthCode);
                                    updateSql.append("' ");
                                    log.info("updateSql:" + updateSql.toString());
                                    // 修改营销活动事项台账 已使用金额 sum(台账明细*清算金额），已入账金额 sum(明细数据.入账金额），已请款金额 sum(明细数据.请款金额）
                                    rst.executeUpdate(updateSql.toString());
                                    // 提交事务
                                    rst.commit();
                                } catch (Exception e) {
                                    // 回滚
                                    rst.rollback();
                                    log.error("修改数据异常：" + e.getMessage());
                                }
                            }else {
                                log.error("获取统计金额为空！");
                            }
                        }
                    }

                } else {
                    log.error("根据营销活动事项台账formId查询数据库表名失败！");
                }
            } else {
                log.error("活动是否核销枚举为空或找不到！");
            }
        } catch (Exception e) {
            log.error("定时任务异常：" + e.getMessage());
        }
    }

    private JSONObject getSumAmountOfMoney(String actAuthCode){
        RecordSet rs = new RecordSet();
        try {
            // 营销活动日报表台账表单id
            int reportFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_daily_report_form_id"));

            // 获取营销活动日报表台账主表表名
            String reportFormTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(reportFormId);
            log.info("获取营销活动日报表台账主表表名："+reportFormTableName);
            if(StrUtil.isNotBlank(reportFormTableName)){
                // 查询枚举 日报流水类型 正常数据
                String selectValueNormalData = com.customization.unionpay.market.util.FormDataUtils.getItemValue(reportFormId, "rblslx", "正常数据");
                log.info("正常数据枚举值："+selectValueNormalData);
                // 查询枚举 日报流水类型 核定金额变更数据
                String selectValueApprovedChangeData = FormDataUtils.getItemValue(reportFormId, "rblslx", "核定金额变更数据");
                log.info("核定金额变更数据枚举值："+selectValueApprovedChangeData);

                StringBuilder sql = new StringBuilder("select sum(qsje) as qs,sum(rzje) as rz,sum(qkje) as qk from ");
                sql.append(reportFormTableName);
                sql.append(" where 1=1 and yxpthdsqm='");
                sql.append(actAuthCode);
                sql.append("' and ");
                sql.append("(rblslx='").append(selectValueNormalData).append("' or rblslx='").append(selectValueApprovedChangeData).append("') ");
                log.info("sql:"+sql.toString());
                rs.executeQuery(sql.toString());
                JSONObject result = new JSONObject();
                if (rs.next()) {
                    String qs = Util.null2String(rs.getString("qs"));
                    String rz = Util.null2String(rs.getString("rz"));
                    String qk = Util.null2String(rs.getString("qk"));
                    result.put("qs", "".equals(qs)?0:qs);
                    result.put("rz", "".equals(rz)?0:rz);
                    result.put("qk", "".equals(qk)?0:qk);
                    return result;
                }else {
                    log.error("查询获取营销活动日报表台账数据异常!");
                }
            }else {
                log.error("查询获取营销活动日报表台账主表表名异常!");
            }
        }catch (Exception e){
            log.error("查询异常："+e.getMessage());
        }
        return null;
    }
}
